package com.huhao.wshare.Friends;

import static com.huhao.wshare.Config.ACCEPT_FRIEND_REQUEST;
import static com.huhao.wshare.Config.FIND_USER_ID;
import static com.huhao.wshare.Config.GET_PENDING_FRIEND_REQUEST;
import static com.huhao.wshare.Config.REJECT_FRIEND_REQUEST;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.tabs.TabLayout;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddFriendActivity extends BaseActivity implements PendingFriendRequestAdapter.OnRequestActionListener {

    private EditText etFriendAccount;
    private Button btnAddFriend;
    private OkHttpClient client = new OkHttpClient();
    private String token;
    private RecyclerView rvRequests;
    private TabLayout tabLayout;
    private PendingFriendRequestAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<JSONObject> sentRequests = new ArrayList<>();
    private List<JSONObject> receivedRequests = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_add_friend);

        // 初始化视图组件
        etFriendAccount = findViewById(R.id.et_user_account);
        btnAddFriend = findViewById(R.id.btn_search_user);
        tabLayout = findViewById(R.id.tabLayout);
        rvRequests = findViewById(R.id.rv_requests);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        token = sp.getString("token", null);

        // 设置 RecyclerView
        adapter = new PendingFriendRequestAdapter();
        rvRequests.setLayoutManager(new LinearLayoutManager(this));
        rvRequests.setAdapter(adapter);

        // 设置适配器的监听器
        adapter.setOnRequestActionListener(this);

        // 获取待处理的好友请求
        getPendingFriendRequests();

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(this::getPendingFriendRequests);

        // 设置 TabLayout 切换监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        adapter.setPendingRequests(sentRequests);
                        break;
                    case 1:
                        adapter.setPendingRequests(receivedRequests);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        btnAddFriend.setOnClickListener(v -> {
            String identifier = etFriendAccount.getText().toString();
            if (!identifier.isEmpty() && token != null) {
                searchUser(identifier);
            } else {
                Toast.makeText(this, "请输入有效信息或重新登录", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onAcceptRequest(int requestId) {
        showAcceptFriendDialog(requestId);
    }

    @Override
    public void onRejectRequest(int requestId) {
        rejectFriendRequest(requestId);
    }


    /**
     * 显示接受好友请求的备注输入对话框
     */
    private void showAcceptFriendDialog(int requestId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("接受好友请求");

        // 加载输入框
        final EditText input = new EditText(this);
        input.setHint("添加备注...(选填)");
        builder.setView(input);

        // 设置确认按钮
        builder.setPositiveButton("确认", (dialog, which) -> {
            String remark = input.getText().toString().trim();
            if (TextUtils.isEmpty(remark)) {
                remark = "";
            }
            acceptFriendRequest(requestId, remark);
        });

        // 设置取消按钮
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }


    /**
     * 拒绝好友请求
     */
    private void rejectFriendRequest(int requestId) {
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载提示
        swipeRefreshLayout.setRefreshing(true);

        String url = REJECT_FRIEND_REQUEST + "/" + requestId;
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(AddFriendActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    swipeRefreshLayout.setRefreshing(false);
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                runOnUiThread(() -> swipeRefreshLayout.setRefreshing(false));

                if (response.isSuccessful()) {
                    String respStr = response.body() != null ? response.body().string() : "";
                    try {
                        JSONObject json = new JSONObject(respStr);
                        int code = json.optInt("code");
                        if (code == 200) {
                            runOnUiThread(() -> {
                                Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show();
                                // 拒绝成功后刷新请求列表
                                getPendingFriendRequests();
                            });
                        } else {
                            runOnUiThread(() ->
                                    Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show()
                            );
                        }
                    } catch (Exception e) {
                        runOnUiThread(() ->
                                Toast.makeText(AddFriendActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show()
                        );
                    }
                } else {
                    runOnUiThread(() ->
                            Toast.makeText(AddFriendActivity.this, "操作失败，请重试", Toast.LENGTH_SHORT).show()
                    );
                }
            }
        });
    }

    private void acceptFriendRequest(int requestId, String remark) {
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载提示
        swipeRefreshLayout.setRefreshing(true);

        try {
            // 构建请求体，包含可选的remark字段
            JSONObject requestBodyJson = new JSONObject();
            requestBodyJson.put("remark", remark);

            // 定义请求体的媒体类型
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(requestBodyJson.toString(), JSON);

            String url = ACCEPT_FRIEND_REQUEST + "/" + requestId;
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + token)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    runOnUiThread(() -> {
                        Toast.makeText(AddFriendActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    });
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    runOnUiThread(() -> swipeRefreshLayout.setRefreshing(false));

                    if (response.isSuccessful()) {
                        String respStr = response.body() != null ? response.body().string() : "";
                        try {
                            JSONObject json = new JSONObject(respStr);
                            int code = json.optInt("code");
                            if (code == 200) {
                                runOnUiThread(() -> {
                                    Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show();
                                    // 接受成功后刷新请求列表
                                    getPendingFriendRequests();
                                });
                            } else {
                                runOnUiThread(() ->
                                        Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show()
                                );
                            }
                        } catch (Exception e) {
                            runOnUiThread(() ->
                                    Toast.makeText(AddFriendActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show()
                            );
                        }
                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(AddFriendActivity.this, "操作失败，请重试", Toast.LENGTH_SHORT).show()
                        );
                    }
                }
            });
        } catch (JSONException e) {
            runOnUiThread(() -> Toast.makeText(this, "构建请求体失败", Toast.LENGTH_SHORT).show());
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    private void getPendingFriendRequests() {
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            return;
        }

        String url = GET_PENDING_FRIEND_REQUEST;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(AddFriendActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    if (swipeRefreshLayout.isRefreshing()) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String respStr = response.body() != null ? response.body().string() : "";
                    handlePendingRequestsResponse(respStr);
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(AddFriendActivity.this, "获取待处理好友请求失败", Toast.LENGTH_SHORT).show();
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    });
                }
                runOnUiThread(() -> {
                    if (swipeRefreshLayout.isRefreshing()) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    private void handlePendingRequestsResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONArray data = json.optJSONArray("data");
                sentRequests.clear();
                receivedRequests.clear();

                if (data != null) {
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject request = data.getJSONObject(i);
                        String type = request.optString("type");
                        if ("SENT".equals(type)) {
                            sentRequests.add(request);
                        } else if ("RECEIVED".equals(type)) {
                            receivedRequests.add(request);
                        }
                    }
                }
                runOnUiThread(() -> {
                    // 默认显示第一个标签页数据
                    if (tabLayout.getSelectedTabPosition() == 0) {
                        adapter.setPendingRequests(sentRequests);
                    } else {
                        adapter.setPendingRequests(receivedRequests);
                    }
                });
            } else {
                runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show());
            }
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, "解析待处理好友请求失败", Toast.LENGTH_SHORT).show());
        }
    }

    private void searchUser(String identifier) {
        String url = FIND_USER_ID + "?identifier=" + identifier;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String respStr = response.body() != null ? response.body().string() : "";
                    handleSearchResponse(respStr);
                } else {
                    runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, "用户不存在，请检查输入", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void handleSearchResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONObject data = json.optJSONObject("data");
                if (data != null) {
                    long userId = data.optLong("userId");
                    boolean isFriend = data.optBoolean("isFriend");
                    Intent intent = new Intent(AddFriendActivity.this, AddFriendProfileActivity.class);
                    intent.putExtra("userId", userId);
                    intent.putExtra("isFriend", isFriend);
                    startActivity(intent);
                }
            } else {
                runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, json.optString("message"), Toast.LENGTH_SHORT).show());
            }
        } catch (Exception e) {
            runOnUiThread(() -> Toast.makeText(AddFriendActivity.this, "解析用户信息失败", Toast.LENGTH_SHORT).show());
        }
    }
}